package arithmetic.socket.TestNioBIO;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


/**
 *
 * 结果对比:  差不多两倍的速度差距.
 * 810 ms
 * 310 ms
 *
 * 测试nio的零拷贝和bio的上传速度
 *
 * @author jiangfeng
 * Created on 2020-03-28
 */
public class NioServer {

    public static void main(String[] args) throws IOException, InterruptedException {
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        executorService.execute(() -> {
            try {
                startServer();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        TimeUnit.SECONDS.sleep(2);
        client();
    }


    // 传输完成:790130688 耗时:9643
    // 传输完成:790128548 耗时:319
    // 传输完成:790128548 耗时:315
    public static void startServer() throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8899));
        SocketChannel channel = serverSocketChannel.accept();

        System.out.println("开始连接:"+channel.getRemoteAddress());
        // 一页
        ByteBuffer byteBuffer = ByteBuffer.allocate(4096);

        int readbuf = 0;
        long l = System.currentTimeMillis();
        while (true) {
            int read = channel.read(byteBuffer);
            if (read == -1) {
                break;
            }
            readbuf += read;
            // (倒带)重新写 或者重新读
            byteBuffer.rewind();
           // System.out.println(readbuf);
        }
        System.out.println("传输完成:" + readbuf + " 耗时:" + (System.currentTimeMillis() - l));
    }

    public static void client() throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress(8899));

        String fileidr = "/Users/jiangfeng/Downloads/ideaIU-2019.3.dmg";

        FileInputStream fileInputStream = new FileInputStream(fileidr);
        FileChannel channel = fileInputStream.getChannel();

        channel.transferTo(0, channel.size(), socketChannel);

        channel.close();
        socketChannel.close();
    }
}
